package com.itsu.spbspider.controller;

import com.itsu.spbspider.component.task.BaiduNewsCrawlerTask;
import com.itsu.spbspider.entity.Crawler;
import com.itsu.spbspider.entity.Job;
import com.itsu.spbspider.service.CrawlerService;
import com.itsu.spbspider.service.JobService;
import com.itsu.spbspider.util.TaskUtil;
import org.quartz.JobDataMap;
import org.quartz.Trigger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/task")
public class TaskController {

    @Resource
    JobService jobService;

    @Resource
    CrawlerService crawlerService;

    @GetMapping("/startorstop/{id}")
    @ResponseBody
    public Map startOrStop(@PathVariable("id") String id) throws Exception {
        Map map = new HashMap();
        Job job = jobService.getJobById(id);
        job.setErrorCount(0);
        job.setSuccessCount(0);
        Crawler crawler = crawlerService.getCrawlerById(job.getCrawlerId());
        if (job.getStatus().equals("N")) {
            Trigger.TriggerState triggerState = TaskUtil.checkJobScheduler(job.getJobName());
            if (!"NONE".equals(triggerState.name())) {
                TaskUtil.stopJob(job.getJobName());
            }
            JobDataMap jobdataMap = new JobDataMap();
            jobdataMap.put("crawler", crawler);
            jobdataMap.put("job", job);
            TaskUtil.startJob(BaiduNewsCrawlerTask.class, job.getJobName(), job.getTimeInterval(), jobdataMap);
            job.setStatus("Y");
        } else {
            TaskUtil.stopJob(job.getJobName());
            Trigger.TriggerState triggerState = TaskUtil.checkJobScheduler(job.getJobName());
            System.err.println("current job trigger state(stop) : " + triggerState.name());
            job.setStatus("N");
        }
        jobService.updateJob(job);
        map.put("code", 0);
        map.put("msg", "ok");
        return map;
    }
}
